package com.zq.it.service.impl.admin;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.struts2.ServletActionContext;

import com.zq.it.dao.common.PageConfig;
import com.zq.it.pojo.Student;
import com.zq.it.pojo.User;
import com.zq.it.pojo.exam.TNote;
import com.zq.it.pojo.exam.TStudentTask;
import com.zq.it.pojo.exam.data.ObjectData;
import com.zq.it.pojo.exam.data.StudentData;
import com.zq.it.service.admin.StudentService;
import com.zq.it.service.common.BaseServiceImpl;
import com.zq.it.tool.Constant;

public class StudentServiceImpl extends BaseServiceImpl implements StudentService {

	@Override
	public List<Student> getAllStudent() {
		return getStudentDao().findStudentEtyList();
	}

	@Override
	public String creatHql(Student student, String startTime, String endTime) {
		StringBuffer hql = new StringBuffer("from Student as model where 1=1");
		String nameSql = null == student.getStuName()
				|| "".equals(student.getStuName())
						? ""
						: " and model.stuName like '%"
								+ student.getStuName() + "%'";
		String sexSql = student.getStuSex().isEmpty()
				? ""
				: " and model.sex =" + student.getStuSex();
		String idcardSql = null == student.getStuIdc()
				|| "".equals(student.getStuIdc())
						? ""
						: " and model.stuIdc like '%" + student.getStuIdc()
								+ "%'";
		String classSql = student.getTclass().getClassId() < 0
				? ""
				: " and model.tclass.classId =" + student.getTclass().getClassId();
		String snoSql = null == student.getTclass().getClassId()
				|| "".equals(student.getTclass().getClassId())
						? ""
						: " and model.stuIdc like '%"
								+ student.getStuIdc() + "%'";
		String startTimeHql = null == startTime || "".equals(startTime)
				? ""
				: " and model.createTime >= '" + startTime + "'";
		String endTimeHql = null == endTime || "".equals(endTime)
				? ""
				: " and model.createTime <= '" + endTime + "'";
		hql.append(nameSql).append(sexSql).append(classSql).append(snoSql)
				.append(startTimeHql).append(endTimeHql).append(idcardSql);
		return hql.toString();
	}

	@Override
	public void removeStudent(Integer id) {
		getStudentDao().deleteStudentEtyByID(id);
	}

	@Override
	public void renewalStudent(Student student) {
		getStudentDao().updateStudentEty(student);
	}

	@Override
	public List getStudent(Integer id) {
		return getStudentDao().findStudentEtyById(id);
	}

	@Override
	public void addStudent(Student student) {
		getStudentDao().saveStudentEty(student);
		getUserDao().saveUserEty(new User(student.getStuId().toString()));
	}

	@SuppressWarnings("deprecation")
	@Override
	public List getStudentListByType(int type, String param) {
		List list = null;
		if (type == 0)
			list = getStudentDao().findStudentEtyById(Long.parseLong(param));
		if (type == 1)
			list = getStudentDao().findStudentEtyByName(param);
		if (type == 2)
			list = getStudentDao().findStudentEtyByHql(
					"from Student where stuIdc like '%" + param + "%'");
		if (type == 3) {
			if (param.equals("0")) {
				list = getStudentDao().findStudentEtyByHql(
						"from Student where tclass.classId=" + null);
			} else {
				list = getStudentDao().findStudentEtyByHql(
						"from Student where tclass.classId="
								+ Integer.parseInt(param));
			}
		}
		return list;
	}

	@Override
	public List getStudentByExmp(Student student) {
		// TODO Auto-generated method stub
		return getStudentDao().findStudentEtyByExmp(student);
	}

	@Override
	public void removeStudent(Student student) {
		// TODO Auto-generated method stub
		getStudentDao().deleteStudentEtyByObj(student);
	}

	@Override
	public void removeAllStudent(long[] ids) {
		getStudentDao().deleteAllEty(ids);
		// TODO Auto-generated method stub

	}

	@Override
	public List<Student> importStudentList(File stuFile) {
		List<Student> stuList = getStuListFromStr(importxlsxFile(stuFile));
		List<Student> existStuList = new ArrayList<Student>();
		for (int i = 0; i < stuList.size(); i++) {
			Student stu = stuList.get(i);
			if (!getStudentDao().findStudentEtyById(stu.getStuId()).isEmpty())
				existStuList.add(stu);
		}
		stuList.removeAll(existStuList);
		if (!stuList.isEmpty()) {
			getStudentDao().saveStudentEtyList(stuList);
			List<User> users = new ArrayList<User>();
			for (Student t : stuList) {
				users.add(new User(t.getStuId().toString()));
			}
			getUserDao().saveUserEtyList(users);
		}
		return existStuList;
	}

	private List<Student> getStuListFromStr(String str) {
		List<Student> list = new ArrayList<Student>();
		String[] firstArray = str.split(";");
		Student student = null;
		for (int i = 0; i < firstArray.length; i++) {
			String[] secondArray = firstArray[i].split(":");
			if (secondArray.length == 7) {
				com.zq.it.pojo.TClass tclass = new com.zq.it.pojo.TClass();
				tclass.setClassId(Integer.parseInt(secondArray[6]));
				student = new Student(Long.parseLong(secondArray[0]),
						secondArray[0], secondArray[1], secondArray[2],
						secondArray[3], secondArray[4], secondArray[5], tclass);
			}
			if (secondArray.length == 6) {
				System.out.println(1);
				student = new Student(Long.parseLong(secondArray[0]),
						secondArray[0], secondArray[1], secondArray[2],
						secondArray[3], secondArray[4], secondArray[5]);
			}
			list.add(student);
		}
		return list;
	}

	// 数据的导出
	@Override
	public ByteArrayInputStream exportStudentList(String[] headTitle,
			List list) {
		// TODO Auto-generated method stub
		return new ByteArrayInputStream(exportToExcel(list, headTitle,
				com.zq.it.tool.HeadTitle.EN_STUDENTHEAD.getArray(),
				"com.zq.it.pojo.Student").toByteArray());
	}

	@Override
	public List getTclassNameAndId() {
		// TODO Auto-generated method stub
		return getClassDao().findClassNameAndId();
	}

	@Override
	public ObjectData getListByPage(PageConfig config) {
		ObjectData students = pageDAO.getData(config);
		List<StudentData> list = new ArrayList<StudentData>();
		StudentData studentData;
		if (students.getList() != null && students.getList().size() > 0) {
			for (Student student : (List<Student>) students.getList()) {
				studentData = new StudentData();
				studentData.setStudent(student);
				studentData.setTclass(
						getClassDao().findById(student.getTclass().getClassId()));
				list.add(studentData);
			}
	   }
		students.setList(list);
		return students;
	}

	@Override
	public StudentData getStudentById(long StudentId) {
		Student student = getStudentDao().findById(StudentId);
		// student.setTAccount(accountDAO.findById(accountId));
		StudentData studentData = new StudentData();
		studentData.setStudent(student);
		studentData.setTclass(
				getClassDao().findById(student.getTclass().getClassId()));
		return studentData;
	}

	@Override
	public void delete(long[] ids) {
		List<TStudentTask> temp;
		for (long id : ids) {
			Student student = getStudentDao().findById(id);
			examDAO.deleteByHql("delete from TExam t where t.Student.id="
					+ student.getId());
			examResultDAO
					.deleteByHql("delete from TExamResult t where t.Student.id="
							+ student.getId());
			noteDAO.deleteByHql("delete from TNote t where t.Student.id="
					+ student.getId());
			temp = studentTaskDAO
					.findByHql("from TStudentTask t where t.Student.id="
							+ student.getId());
			for (TStudentTask stuTask : temp) {
				if (stuTask.getTTask().getCaseType() == 0) {
					deleteDir(new File(Constant.STUDENT_TASK+ stuTask.getTTask().getTaskName() + "/" + student.getStuId() + "/" + stuTask.getTaskFile()));
				} else if (stuTask.getTTask().getCaseType() == 1) {
					deleteDir(new File(Constant.CLASS_TASK + stuTask.getTClassTask().getDir() + "/" + stuTask.getTaskFile()));
				}
			}
			studentTaskDAO.deleteByHql(
					"delete from TStudentTask t where t.Student.id="
							+ student.getId());
			deleteDir(new File(ServletActionContext.getServletContext()
					.getRealPath(Constant.HEAD_PIC + student.getStuHead())));
			getStudentDao().delete(student);
		}

	}

	@Override
	public void updateHead(Student student) {
		getStudentDao().update(student);

	}

	private Student getStudentByNo(String studentNo) {
		List data = getStudentDao().findByStudentNo(studentNo);
		if (null != data && !data.isEmpty()) {
			return (Student) data.get(0);
		} else {
			return null;
		}
	}

	private Student getStudentByRow(HSSFRow row) {
		Student student = new Student();
		try {

			HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
			String studentName = hSSFDataFormatter
					.formatCellValue(row.getCell(0)).trim();
			String sex = hSSFDataFormatter.formatCellValue(row.getCell(1))
					.trim();
			String studentNo = hSSFDataFormatter.formatCellValue(row.getCell(2))
					.trim();
			String idcardNo = hSSFDataFormatter.formatCellValue(row.getCell(3))
					.trim();
			String mobile = hSSFDataFormatter.formatCellValue(row.getCell(4))
					.trim();
			String email = hSSFDataFormatter.formatCellValue(row.getCell(5))
					.trim();
			student.setStuName(studentName);
			if (sex.equals("男"))
				student.setStuSex("0");
			else if (sex.equals("女"))
				student.setStuSex("1");
			student.setStuId(Long.parseLong(studentNo));
			student.setStuIdc(idcardNo);
			student.setContactWay(mobile);
			return student;
		} catch (Exception e) {

			return student;
		}
	}

	@Override
	public void addNotes(TNote note) {
		noteDAO.save(note);
	}

	@Override
	public TNote getNoteById(long[] id) {

		return noteDAO.findById(id[0]);
	}

	@Override
	public void deleteNoteById(long[] ids) {
		for (long id : ids) {

			TNote note = noteDAO.findById(id);
			try {
				noteDAO.delete(note);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public Student getStudentByClassId(long[] id) {
		return (Student) getStudentDao().findByClassId(id[0]);
	}

	@Override
	public void updateStudent(Student student) {
		// TODO Auto-generated method stub
		getStudentDao().update(student);
	}

}
